package br.com.ac.fatureweb.service;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.com.ac.fatureweb.model.Perfil;
import br.com.ac.fatureweb.model.PerfilAcao;
import br.com.ac.fatureweb.utilitary.NgcDefaultBean;

@Local
@Named
@Stateless
public class NgcPerfilBean extends NgcDefaultBean<Perfil> {

	@PersistenceContext
	private EntityManager entityManager;

	@PostConstruct
	void inicialize() {
		setEm(entityManager);
	}

	/**
	 * @author Brunno Gonçalves (brunnogoncalves@gmail.com) 18/03/2015
	 *
	 * @param perfil
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<PerfilAcao> getLstPerfilAcao(Perfil perfil) {

		Query query = entityManager
				.createQuery("SELECT pea FROM PerfilAcao pea WHERE pea.perfil = :perfil ");
		query.setParameter("perfil", perfil);

		return query.getResultList();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @author Brunno Gonçalves (brunnogoncalves@gmail.com) 19/03/2015
	 * 
	 * @see br.com.ac.fatureweb.utilitary.NgcDefaultBean#merge(java.lang.Object)
	 */
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	@Override
	public Perfil merge(Perfil entity) {
		if (entity.getLstPerfilAcaoExcluir() != null) {
			for (PerfilAcao pea : entity.getLstPerfilAcaoExcluir()) {
				if (pea.getId() != null) {
					PerfilAcao perfilAcao = entityManager.getReference(
							PerfilAcao.class, pea.getId());
					entityManager.remove(perfilAcao);
				}
			}
		}
		return entityManager.merge(entity);
	}

	/**
	 * @author Brunno Gonçalves (brunnogoncalves@gmail.com) 26/03/2015
	 * @param idUsuario
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<PerfilAcao> buscarPerfisAcaoDesassociados(Long idUsuario) {
		Query query = entityManager
				.createQuery("SELECT pea FROM PerfilAcao pea WHERE NOT EXISTS "
						+ " (SELECT pea1 FROM Usuario usu INNER JOIN usu.lstPerfilAcao pea1  WHERE usu.id = :idUsuario "
						+ "		AND pea1 = pea ) ");

		query.setParameter("idUsuario", idUsuario);

		return query.getResultList();
	}

}
